<?php 
set_time_limit(60*10);
define('IN_ECS', true);
require(dirname(__FILE__) . '/includes/init.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>{$app_name}</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<?php



define('GOODS_IMAGE_DIR','../images/');

 $sql = "SELECT `goods_id` FROM ".$GLOBALS['ecs']->table('goods');
 $all = $GLOBALS['db']->getAll($sql);
 $GLOBALS['id_list'] = array();
foreach ($all AS $key=>$val)
{
  $GLOBALS['id_list'][] = $val['goods_id'];
}
echo "<h1>删除商品图片</h1>";
$handle  = opendir(constant('GOODS_IMAGE_DIR'));
while($file = readdir($handle)) 
{
	$newpath=constant('GOODS_IMAGE_DIR').$file;
	
	 if(is_dir($newpath) && preg_match('/^\d+$/',$file) > 0)
	{
		 //goods img
		 $sub_dir = '/goods_img';
		 deleteImageIndir($newpath.$sub_dir);
		 $sub_dir = '/source_img';
		 deleteImageIndir($newpath.$sub_dir);
		 $sub_dir = '/thumb_img';
		 deleteImageIndir($newpath.$sub_dir);
	}
}
closedir($handle);

echo "<h1>删除商品描述图片</h1>";
$handle = opendir(constant('GOODS_IMAGE_DIR').'upload/Image');
while($file = readdir($handle)) 
{
	if($file == '.' || $file == '..')
		continue;
	$refered = checkImageReferByGoodsDesc($file);
	if(!$refered)
	{
		echo "Delete ".constant('GOODS_IMAGE_DIR').'upload/Image/'.$file."<br>";
		unlink(constant('GOODS_IMAGE_DIR').'upload/Image/'.$file);
	}
}
function deleteImageIndir($path)
{
	if(is_dir($path))
	{
		 $handle  = opendir($path);
		 while($file = readdir($handle))
		{
			 if($file == '.' || $file == '..')
				 continue;
			 if(preg_match('/^\d+/',$file) == 0)
					continue;
			if(strpos($file,'_') == -1)
			{
				echo "delete ".$path.'/'.$file."<br>";
				unlink($path.'/'.$file);
			}else{
				$id = substr($file,0,strpos($file,'_'));
				if(!in_array($id,$GLOBALS['id_list']))
				{
					echo "delete ".$path.'/'.$file."<br>";
					unlink($path.'/'.$file);
				}
			}
		}
		closedir( $handle);
	}
}
function checkImageReferByGoodsDesc($fileName)
{
	$sql = "SELECT count(1) AS `ctn` FROM ".$GLOBALS['ecs']->table('goods')." WHERE `goods_desc` like '%".mysql_real_escape_string($fileName)."%'";
	$count1 = $GLOBALS['db']->getOne($sql);
	$sql = "SELECT count(1) AS `ctn` FROM ".$GLOBALS['ecs']->table('article')." WHERE `content` like '%".mysql_real_escape_string($fileName)."%'";
	$count2 = $GLOBALS['db']->getOne($sql);
	return $count1['ctn'] + $count2['ctn'] > 0;
}
?>

</body>
</html>